package com.ruoyi.finance.protal.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * 图片文件转换为Base64格式的工具类
 * author: wangmh
 */
public class ImageToBase64Converter {

    /**
     * 将图片文件转换为Base64格式字符串
     *
     * @param filePath 图片文件路径
     * @return Base64格式字符串
     * @throws IOException 如果读取文件时发生I/O错误
     */
    public static String convertToBase64(String filePath) throws IOException {
        File file = new File(filePath);

        // 检查文件是否存在
        if (!file.exists()) {
            throw new IOException("File does not exist: " + filePath);
        }

        // 检查文件是否可读
        if (!file.canRead()) {
            throw new IOException("Cannot read file: " + filePath);
        }

        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            fileInputStream.read(bytes);
            return Base64.getEncoder().encodeToString(bytes);
        }
    }

    /**
     * 示例用法
     */
    public static void main(String[] args) {
        String filePath = "path/to/your/image.jpg";
        try {
            String base64String = convertToBase64(filePath);
            System.out.println(base64String);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}